package com.java.thread.queue;

import java.util.LinkedList;
import java.util.List;

public class BlockingQueue {

    private List queue = new LinkedList();
    private int  limit = 10;

    public BlockingQueue(int limit){
        this.limit = limit;
    }

    public synchronized void enqueue(Object item)throws InterruptedException  {
        while(this.queue.size() == this.limit) {  // 队列已满，存储元素的线程等待
            wait();
        }
        if(this.queue.size() == 0) {
            // 获取元素的线程都在等待，需唤醒
            notifyAll();
        }
        this.queue.add(item);
    }

    public synchronized Object dequeue()  throws InterruptedException{
        while(this.queue.size() == 0){ // 队列为空，获取元素的线程等待
            wait();
        }
        if(this.queue.size() == this.limit){
            //存储元素的线程都在等待，需唤醒
            notifyAll();
        }
        return this.queue.remove(0);
    }
}
